package com.dongqi.myblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongqi.myblog.exception.NotFoundException;
import com.dongqi.myblog.po.TType;
import com.dongqi.myblog.mapper.TTypeMapper;
import com.dongqi.myblog.po.vo.TypeQuery;
import com.dongqi.myblog.service.TTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dongqi
 * @since 2020-08-03
 */
@Service
public class TTypeServiceImpl extends ServiceImpl<TTypeMapper, TType> implements TTypeService {

    /**
     * 保存类型
     */
    @Override
    @Transactional
    public int saveType(TType type) {
        type.setName(type.getName().trim());
        return this.baseMapper.insert(type);
    }

    /**
     * 根据id回去类型
     */
    @Override
    public TType getTypeById(Long id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 分页查询类型（根据id降序）
     */
    @Override
    public Page<TType> pageType(Long pageNo, Long pageSize) {
        Page<TType> page = new Page<>(pageNo,pageSize);
        QueryWrapper<TType> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        this.baseMapper.selectPage(page, wrapper);
        return page;
    }

    /**
     * 更新类型
     */
    @Override
    @Transactional
    public int updateType(TType type) {
        int result = this.baseMapper.updateById(type);
        if (result==0){
            throw new NotFoundException("不存在该类型");
        }
        return result;
    }

    /**
     * 根据id删除类型
     */
    @Override
    @Transactional
    public int deleteType(Long id) {
        return this.baseMapper.deleteById(id);
    }

    /**
     * 分局名称获取类型
     * @param type
     * @return
     */
    @Override
    public Boolean getTypeByName(TType type) {
        QueryWrapper<TType> wrapper = new QueryWrapper<>();
        wrapper.eq("name",type.getName().trim());
        TType tType = this.baseMapper.selectOne(wrapper);
        if (tType==null){
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取首页的类型（降序排列）
     */
    @Override
    public List<TypeQuery> getTypeIndex(Integer pageSize){
        return this.baseMapper.selectTypeList(pageSize);
    }

    /**
     * 获取所有类型（降序排列）
     */
    @Override
    public List<TypeQuery> getAllType(){
        return this.baseMapper.selectTypeListAll();
    }

}
